import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Heand from '../component/heand';
import { isLogined } from "./auth";
import { useNavigate } from "react-router-dom";
import { Input, Button, Cascader } from 'antd';

function Add_products() {
  const [name, setName] = useState('');
  const [image, setImage] = useState(null);
  const [imageUrl, setImageUrl] = useState('');
  const [price, setPrice] = useState('');
  const [bcid, setBcid] = useState('')

  const navigate = useNavigate()
  const handleNameChange = (event) => {
    setName(event.target.value);
  };




  useEffect(() => {
    if (isLogined() === false) {

      navigate('/login')


    }
  })

  const handleImageChange = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onloadend = () => {
      setImage(file);
      setImageUrl(reader.result);
    };

    if(file instanceof Blob)
    {
       reader.readAsDataURL(file);
    }
   


  };

  const handlePriceChange = (event) => {
    setPrice(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();

    // 上传图片到LeanCloud
    const formData = new FormData();
    formData.append('file', image);
    formData.append('name', image.name);
    axios.post('https://api.leancloud.cn/1.1/files/file', formData, {
      headers: {
        " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
        "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
        'Content-Type': 'image/jpeg'
      }
    })
      .then(response => {
        const imageUrl = response.data.url;

        // 将商品信息添加到LeanCloud
        axios.post('https://api.leancloud.cn/1.1/classes/bscs', {
          xiangqing: name,
          image: imageUrl,
          price: price,
          people_id: sessionStorage.getItem('username'),
          bcid: bcid
        }, {
          headers: {

            " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
            "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
            'Content-Type': 'application/json',
          }
        })
          .then(() => {
            // 添加成功后的处理逻辑
            console.log('商品添加成功');
            setName('')
            setImage('')
            setImageUrl('')
            setPrice('')
            setBcid('')
            navigate('/login')
          })
          .catch(error => {
            // 添加失败后的处理逻辑
            console.error('商品添加失败', error);
          });
      })
      .catch(error => {
        // 图片上传失败后的处理逻辑
        console.error('图片上传失败', error);
      });
  };
  console.log(isLogined())

  const options = [
    {
      value: '1',
      label: '鞋子',
    },
    {
      value: '7',
      label: '衣服',

    },
    {
      value: '2',
      label: '背包',
    },
    {
      value: '3',
      label: '手机',

    },
    {
      value: '6',
      label: '电脑',
    },
    {
      value: '8',
      label: '首饰品',

    },
    {
      value: '4',
      label: '生活用品',
    },
    {
      value: '5',
      label: '其他',

    },
  ];

  const onChange = (value) => {
    console.log(value[0])
    setBcid(value[0])
    // console.log(bcid)
  }
  useEffect(()=>{
    setBcid(bcid)
    console.log(bcid)
  },[bcid])

  return (

    <div className='pushinput'>
      <Heand />

      <form className='pushtj' >
        <div>
          <label htmlFor="name">商品名字：</label>
          <Input className="xqinp" type="text" id="name" value={name} onChange={handleNameChange} />
        </div>

        <div>
          <label htmlFor="price">商品价格：</label>
          <Input className="xqinp" type="text" id="price" value={price} onChange={handlePriceChange} />
        </div>
        <div>
          <label htmlFor="image">商品图片：</label>
          <Input className="xqinp" type="file" id="image" onChange={handleImageChange} />
          {imageUrl && <img className='pushimage' src={imageUrl} alt="商品图片" />}
        </div>
        <div>
          <Cascader options={options} onChange={onChange} placeholder="Please select" />
        </div>

        <Button onClick={handleSubmit} >添加商品</Button>
      </form>
    </div>
  )
}

export default Add_products;